package com.gulimall.auth.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.guli.common.utils.HttpUtils;
import com.guli.common.utils.MemberVo;
import com.guli.common.utils.R;
import com.guli.common.vo.WeiboAccessVo;
import com.gulimall.auth.feignservice.FeignMemberService;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.HashMap;

/**
  * @author: 朱财艺
  * @date : 2022/02/08
  * @Description:
    */
@Controller
public class WebController {

    @Autowired
    private FeignMemberService feignMemberService;

    @RequestMapping(value = {"/","/login"})
    public String login(){

        return "login";
    }

    @RequestMapping(value = {"register"})
    public String register(){

        return "register";
    }

    @GetMapping("/oauth2.0/weibo/success")
    public String weiboSuccess(String code, HttpSession session, Model model) throws Exception {
        System.out.println(code);

        //  换取access_token https://api.weibo.com/oauth2/access_token
        HashMap<String, String> map = new HashMap<>();
        map.put("client_id","1319889574");
        map.put("client_secret","2c89ba21c0ae28f9b34819b1e2b7b80e");
        map.put("grant_type","authorization_code");
        map.put("redirect_uri","http://auth.gulimall.com/oauth2.0/weibo/success");
        map.put("code",code);

        HttpResponse httpResponse = HttpUtils.doPost("https://api.weibo.com/oauth2/access_token", "", "post", null, map, "");
        String s = EntityUtils.toString(httpResponse.getEntity());
        WeiboAccessVo weiboAccessVo = JSON.parseObject(s, new TypeReference<WeiboAccessVo>() {
        });
        System.out.println(weiboAccessVo);

        //feign通过用户模块  完成注册或登录
        if(! CheckObjectNull.checkObjAllFieldsIsNull(weiboAccessVo)){
            R r = feignMemberService.weiboLogin(weiboAccessVo);
            if(r.getCode() == 0){//远程调用成功
                MemberVo memberVo = r.getData(new TypeReference<MemberVo>() {
                });
                session.setAttribute("user",memberVo);
                //登录成功 跳转首页
                return "redirect:http://gulimall.com";
            }
        }
        model.addAttribute("error","登录失败");
        return "login";


    }




}
